package com.cheetah.start.module.system.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.cheetah.start.common.annotation.Log;
import com.cheetah.start.common.base.result.Result;
import com.cheetah.start.common.base.result.ResultController;
import com.cheetah.start.common.enums.BusinessTypeEnum;
import com.cheetah.start.common.enums.LogTypeEnum;
import com.cheetah.start.common.utils.MyPasswordUtil;
import com.cheetah.start.module.system.domain.SysAdmin;
import com.cheetah.start.module.system.service.SysAdminService;
import com.cheetah.start.module.system.domain.SysDictData;
import com.cheetah.start.module.system.service.SysDictDataService;
import com.cheetah.start.module.system.domain.SysRole;
import com.cheetah.start.module.system.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.constraints.NotBlank;
import java.util.List;

/**
 * @author Feel
 * @create 2021/7/18
 **/
@Api(tags = {"后台用户"})
@Slf4j
@Validated
@RestController
@RequestMapping("/system/admin")
public class SysAdminController extends ResultController {

    @Autowired
    private SysAdminService sysAdminService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysDictDataService sysDictDataService;

    /**
     * 列表页面
     *
     * @return {@link ModelAndView}
     */
    @ApiOperation("用户管理")
    @GetMapping("/data")
    public ModelAndView list(ModelAndView modelAndView) {
        List<SysDictData> dictData = sysDictDataService.getByDictCode("sex");
        modelAndView.addObject("dictSex", dictData);
        modelAndView.setViewName("/system/user/list");
        return modelAndView;
    }

    /**
     * 添加页面
     *
     * @param modelAndView 模型和视图
     * @return {@link ModelAndView}
     */
    @ApiOperation("用户添加页面")
    @GetMapping("/add")
    public ModelAndView addView(ModelAndView modelAndView) {
        List<SysRole> list = sysRoleService.listEnable();
        modelAndView.addObject("sysRoles", list);
        List<SysDictData> dictData = sysDictDataService.getByDictCode("sex");
        modelAndView.addObject("dictSex", dictData)
                .setViewName("/system/user/add");
        return modelAndView;
    }

    @ApiOperation("用户编辑页面")
    @GetMapping("/edit")
    public ModelAndView edit(ModelAndView modelAndView, Integer adminId) {
        List<SysDictData> dictData = sysDictDataService.getByDictCode("sex");
        modelAndView.addObject("dictSex", dictData)
                .addObject("sysUser", sysAdminService.getById(adminId))
                .addObject("sysRoles", sysRoleService.getAllRoleWithCheck(adminId))
                .setViewName("/system/user/edit");
        return modelAndView;
    }


    /**
     * 登录
     *
     * @param sysAdmin 系统管理员
     * @return {@link Result}
     */
    @ApiOperation(value = "后台登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "账户", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String")
    })
    @PostMapping("/login")
    @Log(title = "后台登录", describe = "登录", type = BusinessTypeEnum.QUERY, logType = LogTypeEnum.LOGIN)
    public Result login(@Validated SysAdmin sysAdmin) {
        SysAdmin one = sysAdminService.getByName(sysAdmin.getName());
        if (one != null) {
            if (MyPasswordUtil.validPassword(one.getPassword(), sysAdmin.getPassword())) {
                StpUtil.login(one.getAdminId(), "PC");
                SaSession saSession = StpUtil.getSession();
                saSession.set("name", one.getName());
                return success("登录成功");
            }
        }
        return failure("账号或密码错误");
    }

    /**
     * 改变
     *
     * @param oldpwd oldpwd
     * @param newpwd newpwd
     * @return {@link Result<?>}
     */
    @ApiOperation(value = "修改密码")
    @Log(title = "用户", describe = "修改密码", type = BusinessTypeEnum.EDIT, logType = LogTypeEnum.OPERATE)
    @PostMapping("/change")
    public Result<?> change(@NotBlank(message = "旧密码不能为空") String oldpwd,
                            @NotBlank(message = "新密码不能为空") String newpwd) {
        int adminId = StpUtil.getLoginIdAsInt();
        SysAdmin admin = sysAdminService.getById(adminId);
        if (MyPasswordUtil.validPassword(admin.getPassword(), oldpwd)) {
            admin.setPassword(MyPasswordUtil.hashPassword(newpwd));
            return decide(sysAdminService.updateById(admin), BusinessTypeEnum.EDIT);
        }
        return failure("密码错误");
    }

    /**
     * 注销
     *
     * @return {@link Result}
     */
    @ApiOperation(value = "退出登录")
    @GetMapping("/logout")
    @Log(title = "用户", describe = "退出登录", type = BusinessTypeEnum.REMOVE, logType = LogTypeEnum.OPERATE)
    public Result logout() {
        StpUtil.logout();
        return success("退出登录");
    }


    /**
     * 信息
     *
     * @return {@link Result}
     */
    @SaCheckLogin
    @ApiOperation(value = "获取登录后台用户信息")
    @GetMapping("/info")
    public Result info() {
        int adminId = StpUtil.getLoginIdAsInt();
        SysAdmin byId = sysAdminService.getById(adminId);
        return success(byId);
    }


}
